package com.jfast.framework.web.core.http;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.util.HttpURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.jfast.framework.log.Logger;
import com.jfast.framework.web.core.JfastConstant;

/**
 * http请求工具类
 * @author zengjintao
 * @version 1.0
 * @createTime 2018年1月19日上午10:53:16
 */
public class JfastHttpRequest {
	
	private static final Logger logger = Logger.getLogger(JfastHttpRequest.class);
	
	/**
	 * http post请求
	 * @param url
	 * @param params
	 * @return
	 */
	public static  String httpPostRequest(String url, Map<String,String> params) {
		HttpClientBuilder builder = HttpClientBuilder.create();
		CloseableHttpClient httpClient = builder.build();
		String content = null;
		try {
			HttpPost httpPost=new HttpPost(url);
			//NameValuePair:代表数据类型
			List<NameValuePair> valuePair = new ArrayList<NameValuePair>();
			Iterator<String> iterator = params.keySet().iterator();
			while(iterator.hasNext()){
				String key = iterator.next();
				valuePair.add(new BasicNameValuePair(key,params.get(key)));
			}
			 // 设置参数  
			httpPost.setEntity(new UrlEncodedFormEntity(valuePair, JfastConstant.ENCODING_DEFAULT)); 
			HttpResponse response = httpClient.execute(httpPost);
			if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK) {
				HttpEntity entity = response.getEntity();
				content = EntityUtils.toString(entity, JfastConstant.ENCODING_DEFAULT);
				try {
					EntityUtils.consume(response.getEntity());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			httpPost.abort();
	        httpPost = null;
		} catch (IOException e) {
			logger.error("http请求异常",e);
		} finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return content;
	}
	
    /**
     * http get请求
     * @param url
     * @return
     */
	public static String httpGet(String url){
		return httpGet(url,JfastConstant.ENCODING_DEFAULT);
	}

	private static String httpGet(String url, String code) {
		HttpClientBuilder builder = HttpClientBuilder.create();
	    CloseableHttpClient httpClient = builder.build();
	    HttpGet httpget = new HttpGet(url);
	    String content = null;
	    try {
			HttpResponse response = httpClient.execute(httpget);
			if(response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){
			    HttpEntity entity = response.getEntity();
			    content = EntityUtils.toString(entity, code);
			    EntityUtils.consume(entity);
			}
			httpget.abort();
			httpget = null;
		} catch (Exception e) {
			logger.error("http请求异常",e);
		}finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return content;
	}
	
	public static String httpPost(String url, String params) {
		return httpPost(url,params,JfastConstant.ENCODING_DEFAULT);
	}

	/**
	 * httpPost请求
	 * @param url
	 * @param params
	 * @param charset
	 * @return
	 */
	private static String httpPost(String url, String params, String charset) {
		HttpClientBuilder builder = HttpClientBuilder.create();
	    CloseableHttpClient httpClient = builder.build();
	    HttpPost post = new HttpPost(url);
	    String content = null;
	    try {
			post.setEntity(new StringEntity(params, charset));//设置参数
	        HttpResponse response = httpClient.execute(post);
	        if(response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){
	        	HttpEntity entity = response.getEntity();//获取响应信息
	        	content = EntityUtils.toString(entity,charset);
	        	EntityUtils.consume(entity);//关闭流
	        }
	        post.abort();
	        httpClient = null;
		} catch (Exception e) {
			logger.error("HTTP请求异常", e);
		}finally {
			if (httpClient != null) {
				try {
					httpClient.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return content;
	}
}
